/**
* @CopyRight tstudy.com.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.group;

import java.util.Date;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.custom.RoundImageView;
import com.tstudy.laoshibang.event.ChangeGroupEvent;
import com.tstudy.laoshibang.event.UpdateInfoEvent;
import com.tstudy.laoshibang.login.LoginActivity;
import com.tstudy.laoshibang.mode.DicMap;
import com.tstudy.laoshibang.mode.TGroup;
import com.tstudy.laoshibang.mode.User;
import com.tstudy.laoshibang.mode.response.GroupDetailResponse;
import com.tstudy.laoshibang.profile.MyCommunityFragment;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import de.greenrobot.event.EventBus;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;
@SuppressLint("InflateParams")
@EFragment(R.layout.group_profile)
public class GroupProfileFragment extends BaseFragment{
	final static String TAG = "group_profile";
	String mGroupId;
	TGroup mGroup;
	public GroupProfileFragment() {
		super();
	}
	
	@ViewById(R.id.group_profile_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.group_profile_progress)
	RelativeLayout mProgressLayout;
	
	@ViewById(R.id.group_profile_title)
	TextView mTitleTxt;
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;

	public static void add(int containerViewId,String groupId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		args.putString(CONSTANT.ARGS.GROUP_ID, groupId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,GroupProfileFragment_.class.getName(),args);
		((BaseActivity)BaseApplication.mCurrentActivity).add(containerViewId,fragment,TAG);	
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
//		EventBus.getDefault().register(this);
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			mRootLayout.setOnClickListener(null);
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					getGroupProfile(mGroupId);
				}
			}, CONSTANT.LOAD_DATA_DELAY_TIME);
			
		}
	}
	
	
	
	@Click({R.id.group_profile_back})
	public void actionClick(View view){
		switch (view.getId()) {
		case R.id.group_profile_back:
			backAction(mFragmentId);
			break;
		default:
			break;
		}
	}
	
	@ViewById(R.id.group_profile_avatar)
	ImageView mGroupAvatar;
	@ViewById(R.id.group_profile_owner_avatar)
	ImageView mOwnerAvatar;
	@ViewById(R.id.group_profile_name)
	TextView mGroupName;
	@ViewById(R.id.group_profile_district)
	TextView mGroupDisctrct;
	@ViewById(R.id.group_profile_member_count)
	TextView mGroupMemberCount;
	@ViewById(R.id.group_profile_introduce_desc)
	TextView mGroupIntroduce;
	@ViewById(R.id.group_profile_createtime_value)
	TextView mGroupCreateTime;
	@ViewById(R.id.group_profile_apply)
	TextView mGroupApply;
	@ViewById(R.id.group_profile_owner_name)
	TextView mGroupOwnerName;
	@ViewById(R.id.group_profile_member_avatar_layout)
	RelativeLayout mGroupMemberAvatarLayout;
	
	public void setView(){
		mTitleTxt.setVisibility(View.VISIBLE);
		mGroupName.setText(mGroup.name);
		mGroupDisctrct.setText(mGroup.province.text);
		mGroupMemberCount.setText(mGroup.memberCn + "人");
		mGroupIntroduce.setText(mGroup.description);
		if (!TextUtils.isEmpty(mGroup.createTime)) {
			mGroupCreateTime.setText(CommonUtil.getDateStr(new Date(Long.parseLong(mGroup.createTime))));
		}
		if (mGroup.supers != null && mGroup.supers.size() > 0) {
			mGroupOwnerName.setText(mGroup.supers.get(0).nick);
			HttpManager.getInstance().loadEditAvatar(mOwnerAvatar,mGroup.supers.get(0).imgIdxName,R.drawable.myhome_headerimgbg);
		}
		if (mGroup.cms != null && mGroup.cms.size() > 0) {
			fillMemberLayout();
		}
		changeStatus(mGroup.status);
		HttpManager.getInstance().loadEditAvatar(mGroupAvatar,mGroup.imgIdxName,R.drawable.myhome_headerimgbg);
		
	}
	
	public void changeStatus(DicMap status){
		if (status != null) {
			switch (status.key) {
			case CONSTANT.GROUP_APPLY_INIT:
				mGroupApply.setText(BaseApplication.getResString(R.string.group_apply));
				mGroupApply.setBackgroundResource(R.drawable.red_corner_view);
				mGroupApply.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (BaseApplication.checkLogin()) {
							groupApply(mGroup);
						}else{
							LoginActivity.show();
						}
						
					}
				});
				break;
			case CONSTANT.GROUP_APPLY_ING:
				mGroupApply.setBackgroundResource(R.drawable.red_corner_view_disable);
				mGroupApply.setText(BaseApplication.getResString(R.string.group_apply_ing));
				mGroupApply.setOnClickListener(null);
				break;
			case CONSTANT.GROUP_APPLY_FAILED:
				mGroupApply.setBackgroundResource(R.drawable.red_corner_view);
				mGroupApply.setText(BaseApplication.getResString(R.string.group_apply));
				mGroupApply.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						groupApply(mGroup);
					}
				});
				break;
			case CONSTANT.GROUP_APPLY_SUCCESS:
				mGroupApply.setBackgroundResource(R.drawable.red_corner_view);
				mGroupApply.setText(BaseApplication.getResString(R.string.group_exit));
				mGroupApply.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						groupExit(mGroup);
					}
				});
				break;
			case CONSTANT.GROUP_APPLY_EXIT:
				mGroupApply.setBackgroundResource(R.drawable.red_corner_view);
				mGroupApply.setText(BaseApplication.getResString(R.string.group_apply));
				mGroupApply.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						groupApply(mGroup);
					}
				});
				break;
			default:
				break;
			}
		}
	}
	
	int mLayoutWidth = BaseApplication.mScreenWidth - BaseApplication.getResDimen(R.dimen.group_profile_margain_left);
	int columeSize = 6;
	int mImageMargin = CommonUtil.dip2px(10);
	int mImageWidth = mLayoutWidth/columeSize - mImageMargin;
	public void fillMemberLayout(){
		int size = mGroup.cms.size();
		for (int i = 0; i < size; i++) {
			final User user = mGroup.cms.get(i);
			RoundImageView imgView = new RoundImageView(BaseApplication.mContext);
			imgView.setId(i + 1);
			RelativeLayout.LayoutParams imgLp = new RelativeLayout.LayoutParams(mImageWidth, mImageWidth);
			imgView.setScaleType(ScaleType.CENTER_CROP);
			int rowIndex = i/columeSize;
			int columnIndex = i%columeSize;
			if (rowIndex != 0) {
				imgLp.addRule(RelativeLayout.BELOW,i-columeSize+1);
			}
			if (columnIndex != 0) {
				imgLp.setMargins(0, 0,mImageMargin, mImageMargin);
				imgLp.addRule(RelativeLayout.RIGHT_OF, i);
			}else{
				imgLp.setMargins(0, 0, mImageMargin, mImageMargin);
			}
			HttpManager.getInstance().loadEditAvatar(imgView,user.imgIdxName,R.drawable.profile_avatar_default);
			imgView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					MyCommunityFragment.add(mFragmentId,user.userNo,mGroupId);
				}
			});
			mGroupMemberAvatarLayout.addView(imgView,imgLp);
		}
	}

	private void getGroupProfile(final String groupId){
		BaseListJsonHandler<GroupDetailResponse> response = new BaseListJsonHandler<GroupDetailResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, GroupDetailResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					mGroup = response.data;
					if (mGroup != null) {
						if (TextUtils.isEmpty(groupId)) {//切换到官方群组
							BaseApplication.changeGroupAction(mGroup);
							gotoIndex(mFragmentId);
						}else{//获取组详情
							setView();
						}
					}
				}else{
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					GroupDetailResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected GroupDetailResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,GroupDetailResponse.class);
			}
		};
		if(TextUtils.isEmpty(groupId)){
			HttpManager.getInstance().officialGroup(BaseApplication.mUserNo, response);
		}else{
			HttpManager.getInstance().getGroupDetail(BaseApplication.mUserNo, mGroupId, response);
		}
	}
	
	private void groupApply(final TGroup group){
		if (mIsLoading) {
			return ;
		}
		mIsLoading = true;
		BaseListJsonHandler<GroupDetailResponse> response = new BaseListJsonHandler<GroupDetailResponse>() {
			public void onStart() {
//				if (mLoadType == LoadType.load_first) {
					showProgressBar(mProgressLayout);
//				}
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, GroupDetailResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.data != null) {
						mGroup.status = response.data.status;
						changeStatus(mGroup.status);
						if(mGroup.status.getKey() == CONSTANT.GROUP_APPLY_SUCCESS) {
							BaseApplication.changeGroupAction(mGroup);
							backAction(mFragmentId);
						}
						EventBus.getDefault().post(new ChangeGroupEvent());
					}else{
						BaseApplication.showToast(response.getErrMsg());
					}
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					GroupDetailResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected GroupDetailResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,GroupDetailResponse.class);
			}
		};
		HttpManager.getInstance().groupApply(BaseApplication.mUserNo, group.groupId, "", response);
	}
	
	private void groupExit(final TGroup group){
		if (mIsLoading) {
			return ;
		}
		mIsLoading = true;
		BaseListJsonHandler<GroupDetailResponse> response = new BaseListJsonHandler<GroupDetailResponse>() {
			public void onStart() {
//				if (mLoadType == LoadType.load_first) {
					showProgressBar(mProgressLayout);
//				}
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, GroupDetailResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				afterLoading();
				if (CommonUtil.responseSuccess(response)) {
					mGroup.status.key = CONSTANT.GROUP_APPLY_INIT;
					getGroupProfile(null);
					changeStatus(mGroup.status);
				}else{
					BaseApplication.showToast(response.getErrMsg());
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					GroupDetailResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected GroupDetailResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,GroupDetailResponse.class);
			}
		};
		HttpManager.getInstance().groupExit(BaseApplication.mUserNo, group.groupId, "", response);
	}
	public void afterLoading(){
		mIsLoading = false;
		hideProgressBar(mProgressLayout);
	}
	@Override
	public void clear() {
	}
	
	@Override
	public void onDestroy() {
//		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
			mGroupId = args.getString(CONSTANT.ARGS.GROUP_ID);
		}
	}

}
